﻿using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Products.Repositories;
using mozhi.smarterp.Business.Products;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories.Product
{
    public class ProductInventorySettingRepository : EfCoreRepository<BusinessDbContext, ProductInventorySetting, Guid>, IProductInventorySettingRepository
    {
        public ProductInventorySettingRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<ProductInventorySetting> GetByProductIdAsync(Guid productId)
        {
            var dbContext = await GetDbContextAsync();

            var inventorySetting = await dbContext.Set<ProductInventorySetting>().AsNoTracking()
                .Where(x => x.ProductId == productId).FirstOrDefaultAsync();

            return inventorySetting;
        }

        public async Task<int> GetCountAsync(Guid? productId, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<ProductInventorySetting>().AsNoTracking()
                .WhereIf(productId.HasValue, x => x.ProductId == productId)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .CountAsync();

            return count;
        }


        public async Task<List<ProductInventorySetting>> GetListAsync(List<Guid> productIds, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var inventorySettings = await dbContext.Set<ProductInventorySetting>().AsNoTracking()
                .Where(x => productIds.Contains(x.ProductId))
                .ToListAsync();

            return inventorySettings;
        }
    }
}
